package cn.whitecao.agent.plugin.handler;

import cn.whitecao.agent.core.handler.HandlerLoader;
import cn.whitecao.agent.core.handler.PluginAopHandler;
import net.bytebuddy.asm.Advice;

/**
 * 不要在这里面写静态变量等
 * 这里的代码会被注入进被监视的程序中, 被监视的程序中肯定是没有加载Handler之类的 故而直接new对象会抛类找不到的异常
 * @author : BashfulHuang
 **/
public class ServletInterceptor {


    @Advice.OnMethodEnter()
    public static void enter(
            @Advice.Local("pluginAopHandler") PluginAopHandler pluginAopHandler,
            @Advice.Origin("#m") String methodName,
            @Advice.Origin("#t") String className,
            @Advice.This Object oThis,
            @Advice.AllArguments Object[] args) {
        pluginAopHandler = HandlerLoader.load("cn.whitecao.agent.plugin.handler.ServletHandler");
        pluginAopHandler.before(className,methodName,args,oThis);
    }

    /**
     * 可以把servlet-api的包导进来然后把 req resp强转
     */
    @Advice.OnMethodExit(onThrowable = Throwable.class)
    public static void exit(
            @Advice.Local("pluginAopHandler") PluginAopHandler pluginAopHandler,
            @Advice.Origin("#m") String methodName,
            @Advice.Origin("#t") String className,
            @Advice.This Object oThis,
            @Advice.AllArguments Object[] args,
            @Advice.Thrown Throwable t) {
        pluginAopHandler.after(className,methodName,args,null,oThis,t);
    }
}
